package com.roc.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.roc.dao.DaoException;
import com.roc.dao.IBaseDao;
import com.roc.dao.ISQLBaseDao;
import com.roc.newPage.IPageDao;
import com.roc.pojo.Operators;
import com.roc.pojo.TblMgmRiskRule;
import com.roc.service.RiskRuleMgrService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.SysLogType;
@Service
public class RiskRuleMgrServiceImpl implements RiskRuleMgrService{
	
	private Logger logger=LogManager.getLogger(RiskRuleMgrServiceImpl.class);
	
	@Autowired
	private ISQLBaseDao sqlBaseDao;
	
	@Autowired
	private IBaseDao baseDao;
	
	@Autowired
	private IPageDao pageDao;
	
	@Transactional(rollbackFor = { ServiceException.class })
	@Override
	public synchronized boolean modifyRiskRule(String paramsStr,Operators logingMerchant)
			throws ServiceException {
		try {
			String sql = "update  apstfr.TBL_MGM_RISK_RULE T set T.RISK_NUM_VAULE=? where T.RISK_LEVEL=? "
					+ " AND T.RISK_TRANS_TYPE=? and T.RISK_INFO_TYPE=? "
					+"and T.RISK_NUM_CYCLE=? and T.RISK_KEY_TYPE=? and T.RISK_NUM_TYPE=? and T.RISK_NUM_UNITE=? ";
			
			String sqlV = "update  apstfr.TBL_MGM_RISK_RULE T set T.RISK_NUM_VAULE=? where T.RISK_LEVEL=? "
					+ "AND T.RISK_INS_CD=? AND T.RISK_MCHT_CD = ? AND T.RISK_TRANS_TYPE=? and T.RISK_INFO_TYPE=? "
					+"and T.RISK_NUM_CYCLE=? and T.RISK_KEY_TYPE=? and T.RISK_NUM_TYPE=? and T.RISK_NUM_UNITE=? ";
			if(paramsStr != null && !"".equals(paramsStr)){
				Object[] paramsArray = paramsStr.split(",");
				List<Object> paramsList = Arrays.asList(paramsArray);
				int ui = 0;
				if("V".equals(paramsArray[1])){
					ui = sqlBaseDao.deleteBySql(sqlV, paramsList);
				}else if("E".equals(paramsArray[1])||"F".equals(paramsArray[1])){
					ui = sqlBaseDao.deleteBySql(sql, paramsList);
				}else{
					throw new ServiceException("风控等级参数值错误");
				}
				
				if(ui > 1 || ui<0){
					throw new ServiceException("修改风控规则失败");
				}
				
				baseDao.addSyslog(SysLogType.UPDATE_RISK_RULE.getCode(),
						SysLogType.UPDATE_RISK_RULE.getName(),
						logingMerchant.getAccountNo(), 
						"操作员【" + logingMerchant.getAccountNo()+ "】，修改风控规则【" + paramsStr + "】成功");
				
				return true;
			}else{
				logger.info("修改风控规则参数为空！");
				return false;
			}
		} catch (Exception e) {
			logger.error("修改风控规则异常:{}",e);
			throw new ServiceException("修改风控规则异常");
		}
		
		
	}

	@Transactional(rollbackFor = { ServiceException.class })
	@Override
	public synchronized Map<String,Object> addRiskRules(String mchtCd, String riskLevel,String paramsPosType,Operators logingMerchant)
			throws ServiceException {
		Map<String,Object> resultMap = new HashMap<String, Object>();
		String sql = "SELECT T.RISK_LEVEL,T.RISK_INS_CD,T.RISK_MCHT_CD,T.RISK_TERM_CD,"
				+ "T.RISK_TRANS_TYPE,T.RISK_INFO_TYPE,T.RISK_NUM_CYCLE"
				+",T.RISK_KEY_TYPE,T.RISK_NUM_TYPE,T.RISK_NUM_UNITE,T.RISK_NUM_VAULE,"
				+"T.RISK_CHECK_TIME,T.RISK_WRITE_TIME,"
				+"T.RISK_USE FROM apstfr.TBL_MGM_RISK_RULE t WHERE t.RISK_LEVEL = 'F' AND t.RISK_USE <> '0' ";
		String insertSql = "insert into apstfr.TBL_MGM_RISK_RULE (RISK_LEVEL, "
				+ "RISK_INS_CD, RISK_MCHT_CD, RISK_TERM_CD, RISK_TRANS_TYPE, RISK_INFO_TYPE, "
				+ "RISK_NUM_CYCLE, RISK_KEY_TYPE, RISK_NUM_TYPE, RISK_NUM_UNITE, RISK_NUM_VAULE, "
				+ "RISK_CHECK_TIME, RISK_WRITE_TIME, RISK_USE)"
				+"values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
		String selectSql = "SELECT count(1) FROM apstfr.TBL_MGM_RISK_RULE t WHERE t.risk_mcht_cd=?";
		String selectMerSql = "select t.bank_belong_cd from tbl_mcht_inf t where t.mcht_cd=?";
		String updateMerSql = "update tbl_mcht_inf t set t.ISGROUP='V',t.rec_upd_ts=sysdate,t.OPER_IN='U' where t.mcht_cd=?";
		String insertLevelMgmSql = "insert into apstfr.tbl_mgm_risk_level(RISK_NUM,RISK_NUM_TYPE,RISK_LEVEL) values(?,'mcht','V')";
		String selectLevelSql = "select count(1) from apstfr.tbl_mgm_risk_level t where t.risk_num=?";
		String updateLevelSql = "update apstfr.tbl_mgm_risk_level t set t.risk_level='V' where t.risk_num=?";
		try {
			if(mchtCd == null || "".equals(mchtCd.trim())){
				resultMap.put("flag",false);
				resultMap.put("message", "商户号为空");
				return resultMap;
			}
			if(riskLevel == null || !"V".equals(riskLevel.trim())){
				resultMap.put("flag",false);
				resultMap.put("message", "风控等级值错误");
				return resultMap;
			}
			
			if(!"1".equals(paramsPosType) && !"2".equals(paramsPosType)){
				resultMap.put("flag",false);
				resultMap.put("message", "POS类型值错误");
				return resultMap;
			}
			
			Object[] objParams = new Object[]{mchtCd};
			
			Object bankBelongCd = pageDao.findObj(selectMerSql, objParams);
			if(bankBelongCd == null){
				resultMap.put("flag",false);
				resultMap.put("message", "查询商户机构号失败");
				return resultMap;
			}
			
			//1、传统pos 2、Mpos
			if("1".equals(paramsPosType)){
				sql = sql+" and (t.risk_trans_type like 'POS%' or  t.risk_trans_type like 'ALIPAY%' or t.risk_trans_type like 'WECHAT%' or t.risk_trans_type like 'UNION%')  ";
				selectSql = selectSql+" and (t.risk_trans_type like 'POS%' or  t.risk_trans_type like 'ALIPAY%' or t.risk_trans_type like 'WECHAT%' or t.risk_trans_type like 'UNION%')  ";
				
			}else{
				sql = sql + " and t.risk_trans_type like 'MPOS%'  ";
				selectSql = selectSql + " and t.risk_trans_type like 'MPOS%'  ";
			}
			
			int isExists = Integer.parseInt(String.valueOf(pageDao.findObj(selectSql, objParams))) ;
			if(isExists > 0 ){
				resultMap.put("flag",false);
				resultMap.put("message", "该商户已设置风控规则");
				return resultMap;
			}
			List<Object> objList = pageDao.querySqlAll(sql, null);
			List<TblMgmRiskRule> riskRuleList = new ArrayList<TblMgmRiskRule>();
			dealRiskRuleList(objList, riskRuleList);
			List<Object> paramsList = new ArrayList<Object>();
			for(int i=0;i<riskRuleList.size();i++){
				TblMgmRiskRule risk = riskRuleList.get(i);
				paramsList.clear();
				paramsList.add(riskLevel.trim());
				paramsList.add(String.valueOf(bankBelongCd));
				paramsList.add(mchtCd.trim());
				paramsList.add(risk.getRiskTermCd());
				paramsList.add(risk.getRiskTransType());
				paramsList.add(risk.getRiskInfoType());
				paramsList.add(risk.getRiskNumCycle());
				paramsList.add(risk.getRiskKeyType());
				paramsList.add(risk.getRiskNumType());
				paramsList.add(risk.getRiskNumUnite());
				paramsList.add(risk.getRiskNumValue());
				paramsList.add(risk.getRiskCheckTime());
				paramsList.add(risk.getRiskWriteTime());
				paramsList.add(risk.getRiskUse());
				int insertCount = sqlBaseDao.deleteBySql(insertSql, paramsList);
				if(insertCount != 1){
					throw new ServiceException("风控规则保存异常");
				}
				
			}
			logger.info(logingMerchant.getAccountNo()+"插入商户【"+mchtCd+"】的风控规则完毕");
			
			//添加商户等级管理数据
			paramsList.clear();
			paramsList.add(mchtCd);
			int isLevelExists = Integer.parseInt(String.valueOf(pageDao.findObj(selectLevelSql, new Object[]{mchtCd})));
			if(isLevelExists<=0){
				int levelCount = sqlBaseDao.deleteBySql(insertLevelMgmSql, paramsList);
				if(levelCount != 1){
					throw new ServiceException("商户风控等级信息保存异常");
				}
			}else{
				int updateLevelCount = sqlBaseDao.deleteBySql(updateLevelSql, paramsList);
				if(updateLevelCount != 1){
					throw new ServiceException("商户风控等级信息修改异常");
				}
			}
			
			logger.info(logingMerchant.getAccountNo()+"保存商户【"+mchtCd+"】风控等级信息成功");
			
			//修改商户等级，修改内容包括：商户等级，修改时间，操作标志位
			paramsList.clear();
			paramsList.add(mchtCd);
			int updateCount = sqlBaseDao.deleteBySql(updateMerSql, paramsList);
			if(updateCount != 1){
				throw new ServiceException("商户等级修改异常");
			}
			
			logger.info(logingMerchant.getAccountNo()+"修改商户【"+mchtCd+"】信息成功");
			
			baseDao.addSyslog(SysLogType.INSERT_RISK_RULE.getCode(),
					SysLogType.INSERT_RISK_RULE.getName(),
					logingMerchant.getAccountNo(), 
					"操作员【" + logingMerchant.getAccountNo()+ "】，新增商户【"+mchtCd+"】的风控规则成功");
			
			logger.info(logingMerchant.getAccountNo()+"插入日志完毕");
			
			resultMap.put("flag",true);
			resultMap.put("message", "该商户风控规则设置成功");
			
		} catch (DaoException e) {
			logger.error("新增特约商户风控规则异常！",e);
			throw new ServiceException("新增特约商户风控规则异常！");
		}
		return resultMap;
	}
	
	public void dealRiskRuleList(List<Object> objList,List<TblMgmRiskRule> riskRuleList){
		if(objList != null && objList.size() > 0){
			Iterator it = objList.iterator();
			while(it.hasNext()){
				Object[] obj = (Object[]) it.next();
				TblMgmRiskRule risk = new TblMgmRiskRule();
				risk.setRiskLevel(Constance.Null2EmptyTrim(obj[0]));
				risk.setRiskInsCd(Constance.Null2EmptyTrim(obj[1]));
				risk.setRiskMchtCd(Constance.Null2EmptyTrim(obj[2]));
				risk.setRiskTermCd(Constance.Null2EmptyTrim(obj[3]));
				risk.setRiskTransType(Constance.Null2EmptyTrim(obj[4]));
				risk.setRiskInfoType(Constance.Null2EmptyTrim(obj[5]));
				risk.setRiskNumCycle(Constance.Null2EmptyTrim(obj[6]));
				risk.setRiskKeyType(Constance.Null2EmptyTrim(obj[7]));
				risk.setRiskNumType(Constance.Null2EmptyTrim(obj[8]));
				risk.setRiskNumUnite(Constance.Null2EmptyTrim(obj[9]));
				risk.setRiskNumValue(Constance.Null2EmptyTrim(obj[10]));
				risk.setRiskCheckTime(Constance.Null2EmptyTrim(obj[11]));
				risk.setRiskWriteTime(Constance.Null2EmptyTrim(obj[12]));
				risk.setRiskUse(Constance.Null2EmptyTrim(obj[13]));
				riskRuleList.add(risk);
			}
		}
	}

}
